package com.healthmgmt.common.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.healthmgmt.common.config.AliyunOssConfig;
import com.healthmgmt.common.service.ObjectStorageService;
import com.healthmgmt.common.utils.DateUtils;
import com.healthmgmt.common.utils.uuid.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;

@Service("objectStorageService")
@ConditionalOnProperty(name = "cloud.oss.type", havingValue = "aliyun")
public class AliyunOssServiceImpl implements ObjectStorageService {

    @Autowired
    private AliyunOssConfig config; // 配置类注入

    @Override
    public String uploadFile(MultipartFile file) {
        OSS ossClient = new OSSClientBuilder().build(config.getAliyun().getEndpoint(),
                config.getAliyun().getAccessKeyId(), config.getAliyun().getAccessKeySecret());
        try {
            String dateToStr = DateUtils.parseDateToStr("yyyy/MM/dd", DateUtils.getNowDate());
            String timeFolder = dateToStr + "/";
            String objectKey = timeFolder + UUID.randomUUID() + getFileExtension(file);
            ossClient.putObject(config.getAliyun().getBucketName(), objectKey, file.getInputStream());
            return "https://" + config.getAliyun().getBucketName() + "." + config.getAliyun().getEndpoint() + "/" + objectKey;
        } catch (IOException e) {
            throw new RuntimeException("OSS上传失败", e);
        } finally {
            ossClient.shutdown();
        }
    }

    // 获取文件URL的实现
    @Override
    public String getFileUrl(String objectKey) {
        // 创建OSS客户端
        OSS ossClient = new OSSClientBuilder().build(
                config.getAliyun().getEndpoint(),
                config.getAliyun().getAccessKeyId(),
                config.getAliyun().getAccessKeySecret()
        );

        try {
            // 1. 公共读模式：直接拼接URL
//            if ("public".equalsIgnoreCase(config.getAliyun().getAcl())) {
//                return "https://" + config.getAliyun().getBucketName() + "." + config.getAliyun().getEndpoint() + "/" + objectKey;
//            }
//
//            // 2. 私有模式：生成带签名的临时URL
//            Date expiration = new Date(System.currentTimeMillis() + config.getAliyun().getUrlExpiration() * 1000);
//            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(
//                    config.getAliyun().getBucketName(),
//                    objectKey
//            );
//            request.setExpiration(expiration);
//
//            // 设置响应头（可选）
//            request.setResponseContentType("application/octet-stream");
//
//            URL signedUrl = ossClient.generatePresignedUrl(request);
//            return signedUrl.toString();
            return "https://" + config.getAliyun().getBucketName() + "." + config.getAliyun().getEndpoint() + "/" + objectKey;
        } finally {
            // 确保关闭客户端
            ossClient.shutdown();
        }
    }

    /**
     * 上传到阿里云OSS
     */
    @Override
    public String uploadToOss(byte[] bytes) {
        OSS ossClient = new OSSClientBuilder().build(config.getAliyun().getEndpoint(),
                config.getAliyun().getAccessKeyId(), config.getAliyun().getAccessKeySecret());
        try {
            String dateToStr = DateUtils.parseDateToStr("yyyy/MM/dd", DateUtils.getNowDate());
            String timeFolder = dateToStr + "/";
            String objectKey = timeFolder + UUID.randomUUID() + ".png";
            ossClient.putObject(config.getAliyun().getBucketName(), objectKey, new ByteArrayInputStream(bytes));
            return "https://" + config.getAliyun().getBucketName() + "." + config.getAliyun().getEndpoint() + "/" + objectKey;
        } catch (Exception e) {
            throw new RuntimeException("OSS上传失败", e);
        } finally {
            ossClient.shutdown();
        }
    }

    // 获取文件扩展名（带点）
    private String getFileExtension(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.isEmpty()) {
            return "";
        }

        int dotIndex = originalFilename.lastIndexOf(".");
        if (dotIndex > 0) {
            return originalFilename.substring(dotIndex);
        }
        return "";
    }

}
